package com.cbj.netty.rpc;

import com.cbj.netty.protocol.PackageMsg;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

public class ResponseCallBack{
    // 回调线程池，用于存储线程对应的res结果
    static ConcurrentHashMap<Long, CompletableFuture> mapping = new ConcurrentHashMap<>();
    public static void addCallBack(Long requestID,CompletableFuture callBack){
        mapping.putIfAbsent(requestID,callBack);
    }

    /**
     * @param packageMsg
     */
    public static void runCallBack(PackageMsg packageMsg){
        long requestId = packageMsg.getHeader().getRequestId();
        Object res = packageMsg.getContent().getRes();
        // 一旦调用complete方法，get的阻塞端就会返回结果
        CompletableFuture completableFuture = mapping.get(requestId);
        completableFuture.complete(res);
        // 执行完毕后remove掉
        mapping.remove(packageMsg.getHeader().getRequestId());
    }

}